<?php

include_once $REP_OUTILS . 'Selector.php';
include_once $REP_OUTILS . 'MyException.php';
// Pour FirePHP
include_once($REP_LIB . 'FirePHPCore/FirePHP.class.php');


/**
 * PariGest - class.Operation.php
 *
 * $Id$
 *
 * This file is part of PariGest.
 *
 * Automatically generated on 06.08.2011, 21:02:14 with ArgoUML PHP module 
 * (last revised $Date: 2010-01-12 20:14:42 +0100 (Tue, 12 Jan 2010) $)
 *
 * @author firstname and lastname of author, <author@example.org>
 */

if (0 > version_compare(PHP_VERSION, '5')) {
    die('This file was generated for PHP 5');
}

/**
 * include Compte
 *
 * @author firstname and lastname of author, <author@example.org>
 */
require_once('class.Compte.php');

/**
 * include Pari
 *
 * @author Séb
 */
require_once('class.Pari.php');

/* user defined includes */
// section 127-0-0-1-cd37a3f:130b3771bc2:-8000:0000000000001461-includes begin
// section 127-0-0-1-cd37a3f:130b3771bc2:-8000:0000000000001461-includes end

/* user defined constants */
// section 127-0-0-1-cd37a3f:130b3771bc2:-8000:0000000000001461-constants begin
// section 127-0-0-1-cd37a3f:130b3771bc2:-8000:0000000000001461-constants end

/**
 * Short description of class Operation
 *
 * @access public
 * @author firstname and lastname of author, <author@example.org>
 */
class Operation
{
    // --- ASSOCIATIONS ---
    // generateAssociationEnd :     // generateAssociationEnd :     // generateAssociationEnd : 

    // --- ATTRIBUTES ---
    private $maConnexion;
    /**
     * Short description of attribute IdOperation
     *
     * @access private
     * @var Integer
     */
    private $IdOperation = null;

    /**
     * Short description of attribute IdCompte
     *
     * @access private
     * @var Integer
     */
    private $IdCompte = null;

    /**
     * Short description of attribute Libelle
     *
     * @access private
     * @var String
     */
    private $Libelle = null;

    /**
     * Short description of attribute Date
     *
     * @access private
     * @var Date
     */
    private $Date = null;

    /**
     * Short description of attribute Montant
     *
     * @access private
     * @var UnlimitedInteger
     */
    private $Montant = null;

    /**
     * Type de l'opération
     * (D)épôt, (R)etrait, (P)ari
     *
     * @access private
     * @var Integer
     */
    private $IdType = null;

    /**
     * Short description of attribute Commentaire
     *
     * @access private
     * @var String
     */
    private $Commentaire = null;
    /** Type de dépôt */
    public static $ID_TYPE_DEPOT   = "D";
    /** Type de retrait */
    public static $ID_TYPE_RETRAIT = "R";
    /** Type de pari */
    public static $ID_TYPE_PARI    = "P";
    /** Type de dépôt */
    public static $ID_TYPE_DEPOT_LIB   = "Dépôt";
    /** Type de retrait */
    public static $ID_TYPE_RETRAIT_LIB = "Retrait";
    /** Type de pari */
    public static $ID_TYPE_PARI_LIB    = "Pari";

function __construct($db){
      // Création de la connexion
      $this->maConnexion = $db;
      // Initialisation des requêtes
      $this->initRequete();
      // Préparation des requêtes
      $this->prepare();
      $this->trace = FirePHP::getInstance(true);
}

/**
 * Initialisation des requêtes préparées
 */
private function initRequete(){

      $this->sqlInsert = "INSERT INTO Operation (IdCompte, Libelle, Date, Montant, IdType, Commentaire) VALUES(?, ?, ?, ?, ?, ?)";
      $this->sqlDelete = "DELETE FROM Operation WHERE `IdOperation` = ? and `IdCompte`=?";
      $this->sqlUpdate = "UPDATE Operation SET Libelle= ?, Date= ?, Montant= ?, IdType= ?, Commentaire= ? WHERE `IdOperation` = ? and `IdCompte`=?";
    
}
/**
 * Préparation des requêtes
 */
private function prepare(){

      $this->reqInsert       = $this->maConnexion->prepare($this->sqlInsert);
      $this->reqDelete       = $this->maConnexion->prepare($this->sqlDelete);
      $this->reqUpdate       = $this->maConnexion->prepare($this->sqlUpdate);
    
}

/**
     * Short description of method insertion
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function insertion()
    {
      $this->trace->fb('Operation->insertion : ' . $this->toStringClePrimaire());
      // Requete d'insertion
      $champs = array($this->IdCompte, $this->Libelle, $this->Date, $this->Montant, $this->IdType, $this->Commentaire);
      foreach($champs as $cle=>$valeur)
      {
        $this->trace->fb('cle : ' . $cle . ' - Valeur : '.$valeur);
      }
      try
      {
        // Modification du solde virtuel
        $compte = new Compte($this->maConnexion);
        $compte->setIdCompte($this->getIdCompte());
        $compte->affichage();
        
        $compte->setSolde($compte->getSolde() + $this->getMontant());
        $compte->modification();
        
        $this->reqInsert->execute($champs);
        
        $this->setIdOperation($this->maConnexion->lastInsertId());
        return $this->getIdOperation(); 
      }
      catch(Exception $e)
      {
         //echo 'Erreur : <br>'; print_r($this->reqInsert->errorInfo());
         throw new MyException('Une erreur est survenue lors de l\'insertion de l\'operation.', $this->reqInsert->errorInfo());
      }
    }

    /**
     * Short description of method modification
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function modification()
    {
      $this->trace->fb('modification : ' . $this->toStringClePrimaire());
      // Requete de modification
      $champs = array($this->Libelle, $this->Date, $this->Montant, $this->IdType, $this->Commentaire, $this->IdOperation, $this->IdCompte);

      try
      {
        $operation = new Operation($this->maConnexion);
        $operation->setIdCompte($this->getIdCompte());
        $operation->setIdOperation($this->getIdOperation());
        $operation->affichage();
        
        // Modification du solde
        $compte = new Compte($this->maConnexion);
        $compte->setIdCompte($this->getIdCompte());
        $compte->affichage();
        
        // 
        $compte->setSolde($compte->getSolde() - $operation->getMontant() + $this->getMontant());
        $compte->modification();
        
        $retour = $this->reqUpdate->execute($champs);
        
        return $retour;
      }
      catch(Exception $e)
      {
         //echo 'Erreur : <br>'; print_r($this->reqUpdate->errorInfo());
         throw new MyException('Une erreur est survenue lors de la modification de l\'operation.', $this->reqUpdate->errorInfo());
      }
    }

    /**
     * Short description of method suppression
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function suppression()
    {
      $this->trace->fb('suppression : ' . $this->toStringClePrimaire());
      // Requete de suppression
      try
      {
          $operation = new Operation($this->maConnexion);
          $operation->setIdCompte($this->getIdCompte());
          $operation->setIdOperation($this->getIdOperation());
          $operation->affichage();
          
          // Modification du solde
          $compte = new Compte($this->maConnexion);
          $compte->setIdCompte($this->getIdCompte());
          $compte->affichage();
          
          // Annulation de l'opération dans le solde du compte
          $compte->setSolde($compte->getSolde() - $operation->getMontant());
          $compte->modification();
                    
          $this->reqDelete->execute(array($this->IdOperation, $this->IdCompte));
          $this->trace->fb('suppression réussie');          
      }
      catch(Exception $e)
      {
         //echo 'Erreur : <br>'; print_r($this->reqDelete->errorInfo());
         //throw new Exception('Une erreur est survenue lors de la suppression dans classe. Cause : ' . $e->getMessage() );
         throw new MyException('Une erreur est survenue lors de la suppression de l\'operation. ', $this->reqDelete->errorInfo());
         
      }
    }
    
    /**
    * Short description of method getNextId
    *
    * @access public
    * @author firstname and lastname of author, <author@example.org>
    * @return Integer
    */
    /*public function getNextId()
    {
      $select = new Selector();
    
      // Les Champs
      $select->addChamp('IFNULL(MAX(IdOperation), 0)+1');
    
      // La Table
      $select->addFrom('Operation');
    
      // Les Critères
      $select->addCritere('IdCompte', $this->IdCompte);
    
      $this->trace->fb('Requete : ' . $select->toString());
      //  echo 'requete : ' . $select->toString();
      $stmt = $this->maConnexion->query($select->toString());
      $row = $stmt->fetch();
      //$this->trace->fb('Résultat : ' .  $row[0]);
      return $row[0];
    }*/
    
    /**
     * Short description of method select
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function select($iSensTriP)
    {
      return $this->selectLimit($iSensTriP, -1, -1);
    }
    public function selectLimit($iSensTriP, $iDebutP, $iNbLimitP)
    {
      $select = new Selector();
      $champs = array("IdOperation"=>$this->IdOperation, "IdCompte"=>$this->IdCompte, "Libelle"=>$this->Libelle, "Date"=>$this->Date, "Montant"=>$this->Montant, "IdType"=>$this->IdType, "Commentaire"=>$this->Commentaire);
      
      foreach($champs as $cle=>$valeur) 
      {
        // Les Champs
        $select->addChamp($cle);
        // Les Critères
        if( !empty($valeur) )
         $select->addCritere($cle, $valeur);
      }
      
      $select->addOrderBy(array("Date"), $iSensTriP);
      
      if( $iDebutP != -1 && $iNbLimitP != -1 )
      {
        $select->addLimit($iDebutP, $iNbLimitP);
      }
      
      // La Table
      $select->addFrom('Operation');
      $this->trace->fb('Requete : ' . $select->toString());
      //echo 'requete : ' . $select->toString();
      return $this->maConnexion->query($select->toString());
    }

    /**
     * Short description of method selectLastOperation
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @param  Integer iNbLastOpP
     * @param  Integer iIdCompteP
     * @return mixed
     */
    private function theSelectLastOperation( $iNbLastOpP, $iIdCompteP)
    {
      $select = new Selector();
      $champs = array("IdOperation"=>$this->IdOperation, "IdCompte"=>$this->IdCompte, "Libelle"=>$this->Libelle, "Date"=>$this->Date, "Montant"=>$this->Montant, "IdType"=>$this->IdType, "Commentaire"=>$this->Commentaire);
    
      foreach($champs as $cle=>$valeur)
      {
        // Les Champs
        $select->addChamp($cle);
      }
    
      // Les Critères
      $select->addCritere('IdCompte', $iIdCompteP);
    
      // La Table
      $select->addFrom('Operation');
    
      // clause order by
      $select->addOrderBy(array('IdOperation'), 0);
    
      // La Table
      $select->addLimite($iNbLastOpP);
    
      $this->trace->fb('Requete : ' . $select->toString());
      //echo 'requete : ' . $select->toString();
      return $select;
    }
    
    public function selectLastOperation( $iNbLastOpP, $iIdCompteP)
    {
      return $this->maConnexion->query($this->theSelectLastOperation($iNbLastOpP, $iIdCompteP)->toString());
    }
    
    /**
    * Short description of method selectLastOperation
    *
    * @access public
    * @author firstname and lastname of author, <author@example.org>
    * @param  Integer iNbLastOpP
    * @param  Integer iIdCompteP
    * @return mixed
    */
    public function selectMontantLastOperation( $iNbLastOpP, $iIdCompteP)
    {
      $select = new Selector();
      $select->addChamp('ROUND(SUM(Montant), 2)');

      // La Table
      $select->addFrom('('.$this->theSelectLastOperation( $iNbLastOpP, $iIdCompteP)->toStringSsRequete().') AS LastOp');
    
      $this->trace->fb('Requete : ' . $select->toString());
      //echo 'requete : ' . $select->toString();
      return $this->maConnexion->query($select->toString());
    }
    

    /**
     * Short description of method selectNbOpDuMois
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @param  Integer iMoisP
     * @param  Integer iIdCompteP
     * @return mixed
     */
    public function selectNbOpDuMois( $iMoisP, $iAnneeP, $iIdCompteP)
    {
        $select = new Selector();
        
        // Les Champs
        $select->addChamp('Count(IdOperation)'); 

        // La Table
        $select->addFrom('Operation');
        
        // Les Critères
        $select->addCritere('IdCompte', $iIdCompteP);
        
        $dateDebut = date("Y-m-d", mktime(0, 0, 0, $iMoisP, 01, $iAnneeP));
        $dateMoisSuivant = date("Y-m-d", mktime(0, 0, 0, $iMoisP+1, 01, $iAnneeP));
        
        $select->addCritereSpecif('Date >= '. $dateDebut);
        $select->addCritereSpecif('Date < '. $dateMoisSuivant);
        
        $this->trace->fb('Requete : ' . $select->toString());
        //  echo 'requete : ' . $select->toString();
        return $this->maConnexion->query($select->toString());        
    }

    /**
     * Short description of method selectMontantDuMois
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @param  Integer iMoisP
     * @param  Integer iIdCompteP
     * @return mixed
     */
    public function selectMontantDuMoisEnCours( $iIdCompteP)
    {
      $this->trace->fb('Operation.selectMontantDuMoisEnCours(' . $iIdCompteP . ')');
      return $this->selectMontantDuMois( date("m"), date("Y"), $iIdCompteP, null);
    }
    
    public function selectMontantParisDuMoisEnCours( $iIdCompteP)
    {
      $this->trace->fb('Operation.selectMontantParisDuMoisEnCours(' . $iIdCompteP . ')');
      return $this->selectMontantDuMois( date("m"), date("Y"), $iIdCompteP, Operation::$ID_TYPE_PARI);
    }
    
    private function selectMontantDuMois( $iMoisP, $iAnneeP, $iIdCompteP, $typePariP)
    {
        $select = new Selector();
        
        // Les Champs
        $select->addChamp('ROUND(SUM(Montant), 2)'); 

        // La Table
        $select->addFrom('Operation');
        
        // Les Critères
        $select->addCritere('IdCompte', $iIdCompteP);
        
        $dateDebut = date("Y-m-d", mktime(0, 0, 0, $iMoisP, 01, $iAnneeP));
        $dateMoisSuivant = date("Y-m-d", mktime(0, 0, 0, $iMoisP+1, 01, $iAnneeP));
        
        $select->addCritereSpecif("Date >= '". $dateDebut . "'");
        $select->addCritereSpecif("Date < '". $dateMoisSuivant . "'");
        
        if( $typePariP != null && $typePariP != "" )
        {
          $select->addCritere('IdType', $typePariP);
        }
        
        $this->trace->fb('Requete : ' . $select->toString());
        //  echo 'requete : ' . $select->toString();
        $stmt =  $this->maConnexion->query($select->toString());
        $result = $stmt->fetch();
        return $result[0];
    }

    
    /**
     * Retourne le montant du mois trié part type de pari
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @param  Integer iMoisP
     * @param  Integer iIdCompteP
     * @return mixed
     */
    /*public function selectMntParTypeDuMois( Integer $iMoisP, Integer $iAnneeP,  Integer $iIdCompteP)
    {
        // section 127-0-0-1-cd37a3f:130b3771bc2:-8000:00000000000014C8 begin
        // section 127-0-0-1-cd37a3f:130b3771bc2:-8000:00000000000014C8 end
    }*/

    /**
     * Short description of method affichage
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function affichage()
    {
      $this->trace->fb('Operation->affichage() : ' . $this->toStringClePrimaire());
      $user = new Operation($this->maConnexion);
      $user->setIdCompte($this->getIdCompte());
      $user->setIdOperation($this->getIdOperation());
      // Lecture de la première ligne
      $stmt = $user->select();
      $result = $stmt->fetch();

      $this->IdCompte    = $result['IdCompte'];
      $this->IdOperation = $result['IdOperation'];
      $this->Libelle     = $result['Libelle'];
      $this->Date        = $result['Date'];
      $this->Montant     = $result['Montant'];
      $this->IdType      = $result['IdType'];
      $this->Commentaire = $result['Commentaire'];

      // Fermeture du curseur
      $stmt->closeCursor();
    }

    public function toStringClePrimaire()
    {
      return '|' . $this->IdOperation . '|'. $this->IdCompte . '|';
    }
    
    public function formatLibelle()
    {
      return Operation::getLibelleType($this->IdType);
    }
    
    public static function selectAllTypes()
    {
      $allTypes = array();
      $allTypes[Operation::$ID_TYPE_DEPOT]   = Operation::getLibelleType(Operation::$ID_TYPE_DEPOT);
      $allTypes[Operation::$ID_TYPE_RETRAIT]  = Operation::getLibelleType(Operation::$ID_TYPE_RETRAIT);
      //$allTypes[Operation::$ID_TYPE_PARI] = Operation::getLibelleType(Operation::$ID_TYPE_PARI);
      return $allTypes;
    }
    
    public static function getLibelleType($indTypeP)
    {
      if( $indTypeP == Operation::$ID_TYPE_DEPOT )
      {
        return Operation::$ID_TYPE_DEPOT_LIB;
      }
      if( $indTypeP == Operation::$ID_TYPE_RETRAIT )
      {
        return Operation::$ID_TYPE_RETRAIT_LIB;
      }
      if( $indTypeP == Operation::$ID_TYPE_PARI )
      {
        return Operation::$ID_TYPE_PARI_LIB;
      }
    }
    
    // --- OPERATIONS ---

    /**
     * Short description of method setIdOperation
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setIdOperation($IdOperationP)
    {
        $this->IdOperation = $IdOperationP;
    }

    /**
     * Short description of method getIdOperation
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getIdOperation()
    {
        return $this->IdOperation;
    }

    /**
     * Short description of method setIdCompte
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setIdCompte($IdCompteP)
    {
      $this->IdCompte = $IdCompteP;
    }

    /**
     * Short description of method getIdCompte
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getIdCompte()
    {
      return $this->IdCompte;
    }

    /**
     * Short description of method setLibelle
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setLibelle($LibelleP)
    {
        $this->Libelle = $LibelleP;
    }

    /**
     * Short description of method getLibelle
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getLibelle()
    {
        return $this->Libelle;
    }

    /**
     * Short description of method setDate
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setDate($DateP)
    {
        $this->Date = $DateP;
    }

    /**
     * Short description of method getDate
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getDate()
    {
        return $this->Date;
    }

    /**
     * Short description of method setMontant
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setMontant($MontantP)
    {
        $this->Montant = $MontantP;
    }

    /**
     * Short description of method getMontant
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getMontant()
    {
        return $this->Montant;
    }

    /**
     * Short description of method setIdType
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setIdType($IdTypeP)
    {
        $this->IdType =$IdTypeP; 
    }

    /**
     * Short description of method getIdType
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getIdType()
    {
        return $this->IdType;
    }

    /**
     * Short description of method setCommentaire
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function setCommentaire($CommentaireP)
    {
        $this->Commentaire = $CommentaireP;
    }

    /**
     * Short description of method getCommentaire
     *
     * @access public
     * @author firstname and lastname of author, <author@example.org>
     * @return mixed
     */
    public function getCommentaire()
    {
        return $this->Commentaire;
    }
    
        
} /* end of class Operation */

?>